package com.sinopec.ch34x.device.core.instruct

import cn.wch.ch34xuartdriver.CH34xUARTDriver
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

/**
 * lwj at 2023/5/18
 * 简易读写指令
 */
internal class SimpleInstructAble(
    private val driverRef: () -> CH34xUARTDriver?
) : InstructAble {


    private val byteBuffer = ByteArray(4096)

    override suspend fun write(instruct: Instruct): Boolean {
        return suspendCancellableCoroutine {
            var retval = driverRef.invoke()?.WriteData(instruct.bytes, instruct.bytes.size) ?: -1
            if (retval < 0) {
                it.resume(false)
            } else {
                it.resume(true)
            }
        }
    }

    override suspend fun read(): ByteArray {
        return suspendCancellableCoroutine {
            val readSize = driverRef.invoke()?.ReadData(byteBuffer, byteBuffer.size) ?: 0
            if (readSize > 0) {
                it.resume(byteBuffer.copyOf(readSize))
            } else {
                it.resume(ByteArray(0))
            }

        }
    }
}